import axios from "axios";
import { getToken, removeToken } from "./cookie";
import router from "@/router";

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
//创建实例
//不同的功能,请求的是不同的接口地址
//127.0.0.1:19090/system-公共部分
//超时时间,限制请求时间
const service = axios.create({
    baseURL: "/dev-api",
    timeout: 5000,
})


//请求拦截器
service.interceptors.request.use(
    (config) => {
        if (getToken()) {
            // 设置请求头
            config.headers["Authorization"] = "Bearer " + getToken();
        }
        return config;
    },
    (error) => {
        console.log(error)
        Promise.reject(error);
    }
);



//响应拦截器
// 后端把响应发送前端,先执行
service.interceptors.response.use(
    (res) => {  //res响应数据
        // 未设置状态码则默认成功状态
        const code = res.data.code;
        const msg = res.data.msg;
        if (code == 3001) {
            ElMessage.error(msg);
            removeToken()  //干掉token
            return Promise.reject(new Error(msg))

        }
        else if (code !== 1000) {
            ElMessage.error(msg);
            return Promise.reject(new Error(msg));
        } else {
            return Promise.resolve(res.data);
        }
    },
    (error) => {
        return Promise.reject(error);
    }
);



//http://localhost:5173/dev-spi/sysUser/login

//其它模块可以导入service,暴露出去
export default service
